package ru.spb.bragnikita.myevents.events;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.inject.Named;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Nikita.Brazhnikov
 */
@Named("events")
@SessionScoped
public class EventsListenerBean implements Serializable{

	private static final Logger logger = Logger.getLogger(EventsListenerBean.class.getName());

	private static List<String> options = new LinkedList<String>();

	private String selectedItem;
	private String selectionHistory;

	private String keyWord;


	static {
		options.add("satsugyousuru");
		options.add("sentakusuru");
		options.add("sankaisuru");
		options.add("katazukeru");
	}

	public String getKeyWord() {
		return keyWord;
	}

	public void setKeyWord(String keyWord) {
		this.keyWord = keyWord;
	}

	public List<String> getOptions() {
		return options;
	}

	public String getSelectedItem() {
		return selectedItem;
	}

	public void setSelectedItem(String selectedItem) {
		logger.log(Level.INFO, "Setting selected word to {0}", selectedItem);
		this.selectedItem = selectedItem;
	}

	public String getSelectionHistory() {
		return selectionHistory;
	}

	public void wordChanged(ValueChangeEvent event) {
		String newItem = ObjectUtils.toString(event.getNewValue(), "<nothing>");
		logger.log(Level.INFO, "Value changed by {0}! New item is {1}", new Object[]{event.getComponent().getClientId(), newItem});
		if (selectionHistory == null)
			selectionHistory = newItem;
		else
			selectionHistory = selectionHistory + ", " + newItem;
		if (StringUtils.split(selectionHistory + "", ",").length > 5)
			selectionHistory = StringUtils.substringAfter(selectionHistory, ",");
	}

	public void wordChangedImmediate(ValueChangeEvent event) {
		wordChanged(event);
		FacesContext context = FacesContext.getCurrentInstance();
		context.renderResponse();
	}

	public void validationMethod(FacesContext context, UIComponent component, Object value) {
		logger.log(Level.INFO, "Validation method called for component {0}", component.getClientId());
	}

	public void clean(ActionEvent actionEvent) {
		logger.log(Level.INFO, "Clean action activated by {0}", actionEvent.getComponent().getClientId());
		selectionHistory = null;
	}

	public void cleanImmediate(ActionEvent event) {
		clean(event);
	}

	public String action() {
		logger.log(Level.INFO, "Action is called");
		return null;
	}
}
